package codeRandomThoughts.Test501二叉搜索树中的众数;

import codeRandomThoughts.utils.TreeNode;

import java.util.ArrayList;
import java.util.List;

class Solution2 {
    TreeNode pre;
    List<Integer> modes = new ArrayList<>();
    int maxLen = -1;
    int currLen = 1;

    public int[] findMode(TreeNode root) {
        inorder(root);
        int[] result = new int[modes.size()];
        for (int i = 0; i < result.length; i++) {
            result[i] = modes.get(i);
        }
        return result;
    }

    public void inorder(TreeNode root) {
        if (root == null) return;

        inorder(root.left);
        if (pre == null || root.val != pre.val) {
            currLen = 1;
        } else {
            currLen++;
        }
        if (currLen > maxLen) {
            modes.clear();
            modes.add(root.val);
            maxLen = currLen;
        } else if (currLen == maxLen) {
            modes.add(root.val);
        }
        pre = root;

        inorder(root.right);
    }
}
